﻿using System;
using BoldBrick.Core.Logging;
using Microsoft.SharePoint.Utilities;

namespace BoldBrick.SharePoint.CommonControls.Resources
{
	static class ResourceBuilder
	{
		private static readonly ILogger log = Logger.GetLogger(typeof (ResourceBuilder));
		
		/// <summary>
		/// Common resource file name for BoldBrick.OneIntranet.CommonControls project
		/// </summary>
		public const string ResourceFileName = "BoldBrick.SharePoint.CommonControls";

		/// <summary>
		/// This method gets resource text from solution resource file
		/// </summary>
		/// <param name="resourceName">Name of resource</param>
		/// <param name="language">Language of the resource</param>
		/// <param name="args">Arguments if resource has placeholders</param>
		/// <returns>Returns resource text from solution resource file</returns>
		public static string GetResource(string resourceName, uint? language, params object[] args)
		{
			string resourceKey = string.Format("$Resources: {0}", resourceName);
			language = language ?? 1033;
			
			string resource = SPUtility.GetLocalizedString(resourceKey, ResourceFileName, language.Value);

			if (resource == null)
				return string.Format("#{0}#", resourceName);

			try
			{
				resource = string.Format(resource, args);
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Error, ex, "Cannot replace placeholders.");
			}

			return resource;
		}
		
	}
}
